package com.njtoyo.taxi.admin.logic.business.ride;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.njtoyo.taxi.admin.mapper.master.entity.Refund;
import com.njtoyo.taxi.admin.mapper.master.mapper.RefundMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class RefundLogic {
    @Autowired
    private RefundMapper refundMapper;

    // 生成refund的number，校验是否重复
    public String getSnowflakeId() {
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();

        String key = String.format("B%s", id);
        Integer count = new LambdaQueryChainWrapper<>(refundMapper)
                .eq(Refund::getNumber, key)
                .count();

        if (count > 0) {
            return getSnowflakeId();
        }

        return key;
    }

    // 根据rideOrderId获取refund
    public Refund getByRideOrderId(Long rideOrderId,String refundableType) {
        // 获取refund
        List<Refund> refundList = new LambdaQueryChainWrapper<>(refundMapper)
                .eq(Refund::getRefundableType, refundableType)
                .eq(Refund::getRefundableId, rideOrderId)
                .list();

        if (Objects.nonNull(refundList)) {
            Optional<Refund> first = refundList.stream().findFirst();
            if (first.isPresent()) {
                return first.get();
            }
        }

        return null;
    }

    // 根据 cancellationOrderId 获取refund
    public Refund getByCancellationOrderId(Long cancellationOrderId) {
        // 获取refund
        List<Refund> refundList = new LambdaQueryChainWrapper<>(refundMapper)
                .eq(Refund::getRefundableType, "CancellationOrder")
                .eq(Refund::getRefundableId, cancellationOrderId)
                .list();

        if (Objects.nonNull(refundList)) {
            Optional<Refund> first = refundList.stream().findFirst();
            if (first.isPresent()) {
                return first.get();
            }
        }

        return null;
    }

    public boolean verifyWeCharPayTradeNo(String tradeNo) {
        return ReUtil.isMatch("^42000\\d+$", tradeNo);
    }

}
